package com.gjintel.framework.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.druid.util.StringUtils;
import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.cache.InitCacheData.CacheType;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.res.service.IResService;
import com.gjintel.sdk.util.SpringContextUtil;
import com.gjintel.sdk.util.WordHandler;
import com.gjintel.sdk.util.WordHandlerException;
import com.gjintel.workflow.WorkflowUtils;

/**
 * @author fengya
 * @description 文件资源操作工具类
 * @date 2016-3-15 上午08:26:25
 */
public class FileResUtil {

    /**
     * @param res
     * @return void
     * @description 往文件资源表中增加一个资源数据
     * @author fengya
     * @date 2016-3-15 上午08:26:43
     */
    public static Resources addFileRes(Resources res) {
        IResService resService = (IResService) SpringContextUtil.getBean("resService");
        resService.saveOrUpdate(res);
        InitCacheData.getInstance().initFileData();
        return res;
    }

    /**
     * @param resId
     * @return Resources
     * @description 根据文件资源ID获得资源对象数据
     * @author fengya
     * @date 2016-3-15 上午08:29:14
     */
    public static Resources getResources(String resId) {
        Map<String, Object> fileMap = InitCacheData.getInstance().getCacheData(CacheType.FILE);
        Object obj = fileMap.get(resId);
        return obj == null ? null : (Resources) obj;
    }

    public static void deleteFile(String resId, HttpServletRequest request) {
        IResService resService = (IResService) SpringContextUtil.getBean("resService");
        String filePath = request.getSession().getServletContext().getRealPath("file_resource");
        if (!StringUtils.isEmpty(resId)) {
            Resources res = resService.get(Resources.class, resId);
            if (res != null) {
                File file = new File(filePath + res.getFilePath(), res.getId() + res.getExeName());
                if (file.exists()) {
                    file.delete();
                }
                resService.remove(res);
            }
            InitCacheData.getInstance().initFileData();
        }
    }

    public static void deleteFile(String resId, String rootPath) {
        IResService resService = (IResService) SpringContextUtil.getBean("resService");
        String filePath = rootPath + "file_resource";
        if (!StringUtils.isEmpty(resId)) {
            Resources res = resService.get(Resources.class, resId);
            if (res != null) {
                File file = new File(filePath + res.getFilePath(), res.getId() + res.getExeName());
                if (file.exists()) {
                    file.delete();
                }
                resService.remove(res);
            }
            InitCacheData.getInstance().initFileData();
        }
    }

    /**
     * @param businessId
     * @return List<Resources>
     * @description 根据业务ID获得该业务下所有的文件资源
     * @author fengya
     * @date 2016-3-15 上午08:31:46
     */
    public static List<Resources> findResources(String businessId) {
        IResService resService = (IResService) SpringContextUtil.getBean("resService");
        if (!StringUtils.isEmpty(businessId)) {
            return resService.findResources(businessId);
        }
        return null;
    }

    /**
     * @param businessId
     * @return List<Resources>
     * @description 根据业务ID和功能标示获得该业务下所有的文件资源
     * @author fengya
     * @date 2016-3-15 上午08:31:46
     */
    public static List<Resources> findByBusinessIdAndFlag(String businessId, Integer flag) {
        IResService resService = (IResService) SpringContextUtil.getBean("resService");
        if (!StringUtils.isEmpty(businessId)) {
            return resService.findByBusinessIdAndFlag(businessId, flag);
        }
        return null;
    }

    /**
     * 把文件内容转换成String类型
     *
     * @param fileName
     * @return
     * @throws IOException
     * @author shy
     */
    public static String fileToString(String fileName) throws IOException {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        String fileContent = buffer.toString();
        return fileContent;
    }


    /**
     * 把文件内容转换成String类型
     *
     * @param fileName
     * @return
     * @throws IOException
     * @author ruix
     */
    public static String fileToStringByUTF8(String fileName) throws IOException {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        String fileContent = buffer.toString();
        return fileContent;
    }

    /**
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！)
     *
     * @param res      原字符串
     * @param filePath 文件路径
     * @return 成功标记
     */
    public static boolean string2File(String res, String filePath) {
        boolean flag = true;
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            File distFile = new File(filePath);
            if (!distFile.getParentFile().exists())
                distFile.getParentFile().mkdirs();
            bufferedReader = new BufferedReader(new StringReader(res));
            bufferedWriter = new BufferedWriter(new FileWriter(distFile));
            char buf[] = new char[1024]; // 字符缓冲区
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
            return flag;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * @param path         world保存路径
     * @param map          参数
     * @param worldXmlPath world 文档模板路径
     * @description 生成world
     * @author shy
     * @date 2016-9-11
     */
    public static void generateWord(String path, Map map, String worldXmlPath) {
        WorkflowUtils wfu = new WorkflowUtils();
        System.err.print("world文档生成成功!......");

        WordHandler handler = new WordHandler();
        Writer out;
        try {
            out = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
            handler.write("", worldXmlPath, map, out);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (WordHandlerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得资源文件的绝对路径
     *
     * @return
     */
    public static String getResourcePath() {
        Properties props = new Properties();

        InputStream is = FileResUtil.class.getClassLoader().getResourceAsStream("dataBackUp.properties");
        try {
            props.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return props.getProperty("resource_path");

    }

    /**
     * Gets the root path of server.
     *
     * @return the root path
     */
    public static String getRootPath() {
        String classPath = Thread.currentThread().getContextClassLoader()
                .getResource("").getPath();
        String rootPath = "";

        /** For Windows */
        if ("\\".equals(File.separator)) {
            String path = classPath.substring(1,
                    classPath.indexOf("/WEB-INF/classes"));
            rootPath = path.substring(0, path.lastIndexOf("/"));
            rootPath = rootPath.replace("/", "\\");
        }

        /** For Linux */
        if ("/".equals(File.separator)) {
            String path = classPath.substring(0,
                    classPath.indexOf("/WEB-INF/classes"));
            rootPath = path.substring(0, path.lastIndexOf("/"));
            rootPath = rootPath.replace("\\", "/");
        }
        return rootPath;
    }

}
